package vip.bblog.dynamic.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import vip.bblog.dynamic.datasource.DynamicDataSourceContextHolder;


/**
 * @author An-Il
 */
@Aspect
@Order(-10)
@Component
public class DynamicDataSourceAspect {

    private final static Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    /**
     * 切换aop拦截
     *
     * @param point
     * @param targetDataSource
     * @throws Throwable
     */
    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) throws Throwable {
        String dsId = targetDataSource.value();
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            logger.info("数据源-{}不存在，将使用默认数据源", dsId);
        } else {
            logger.info("当前数据源-{}", dsId);
            DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value());
        }
    }

    /**
     * 切还数据源
     * @param point
     * @param targetDataSource
     */
    @After("@annotation(targetDataSource)")
    public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        logger.info("清除数据源-{}", targetDataSource.value());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
